package com.yvan.periscope;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.alibaba.druid.support.spring.stat.BeanTypeAutoProxyCreator;
import com.alibaba.druid.support.spring.stat.DruidStatInterceptor;
import com.yvan.Conv;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;

@Configuration
@ConditionalOnProperty(name = "yvan.monitor.enable", havingValue = "true")
public class MonitorAutoConfiguration implements InitializingBean {

    @Bean
    @ConfigurationProperties(prefix = "yvan.monitor")
    public MonitorProperties monitorProperties() {
        return new MonitorProperties();
    }

    @Bean
    public ServletRegistrationBean DruidStatViewServle2() {
        final MonitorProperties monitorProperties = monitorProperties();
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), monitorProperties.getDruidServlet());

        //添加初始化参数：initParams
        //白名单：
        //servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
        //servletRegistrationBean.addInitParameter("allow", "*");
        //IP黑名单 (存在共同时，deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page.
        //servletRegistrationBean.addInitParameter("deny","*");

        //登录查看信息的账号密码.
        servletRegistrationBean.addInitParameter("loginUsername", monitorProperties.getDruidLoginName());
        servletRegistrationBean.addInitParameter("loginPassword", monitorProperties.getDruidLoginPassword());
        //是否能够重置数据.
        servletRegistrationBean.addInitParameter("resetEnable", Conv.NS(monitorProperties.isResetEnable()));
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean druidStatFilter2() {
        final MonitorProperties monitorProperties = monitorProperties();
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());

        //添加过滤规则.
        filterRegistrationBean.addUrlPatterns(monitorProperties.getPatterns());

        //添加不需要忽略的格式信息.
        filterRegistrationBean.addInitParameter("exclusions", monitorProperties.getExclusions());
        return filterRegistrationBean;
    }


    @Bean(name = "druid-stat-interceptor")
    public DruidStatInterceptor druidStateInterceptor() {
        return new DruidStatInterceptor();
    }

    @Bean
    public BeanTypeAutoProxyCreator beanTypeAutoProxyCreator() {
        BeanTypeAutoProxyCreator beanTypeAutoProxyCreator = new BeanTypeAutoProxyCreator();
        beanTypeAutoProxyCreator.setTargetBeanType(BeanMonitor.class);
        beanTypeAutoProxyCreator.setInterceptorNames("druid-stat-interceptor");
        return beanTypeAutoProxyCreator;
    }

    @Bean
    public CollectorService collectorService() {
        return new CollectorService();
    }

    @Bean
    public JvmCollectorService jvmCollectorService() {
        return new JvmCollectorService();
    }

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        return new ThreadPoolTaskScheduler();
    }

    public void startCron() {
        //threadPoolTaskScheduler.shutdown();
        threadPoolTaskScheduler().schedule(() -> {
            collectorService().collect();
        }, new CronTrigger(monitorProperties().getCronTable()));

        // JVM 状态收集
        if (monitorProperties().getJvmCronTable() != null && monitorProperties().getJvmCronTable().trim().length() > 0) {
            threadPoolTaskScheduler().schedule(
                    () -> jvmCollectorService().collect(),
                    new CronTrigger(monitorProperties().getJvmCronTable())
            );
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        startCron();
    }

    /*
    @Bean
    public CollectorSchedule collectorSchedule() {
        return new CollectorSchedule();
    }
    */
}
